判断数据类型
方法一:使用 typeof
typeof 并不是一个方法,所以不需要通过()进行调用,只需要在它的后面紧跟我们需要检测的变量就可以,因为它是一个运算符
typeof 能返回的数据类型:number,boolean,string,object,symbol,function,undefined
返回值: typeof 的返回值是一个字符串类型
typeof 1 // 'number'
typeof '' // 'string'
typeof true // 'boolean'
typeof [] // 'object'
typeof {} // 'object'
typeof null // 'object'
typeof undefined // 'undefined'
typeof function () {} // 'function'
注意:其中 null, [], {}都返回 "object",typeof 可以用来检测函数
方法二:使用 instanceof(配合 new 关键字)
instanceof 不能区别 undefined 和 null,而且对于基本类型如果不是用 new 声明的则也测试不出来,对于是使用 new 声明的类型,它还可以检测出多层继承关系。返回 boolean 值
var num2 = new Number()
console.log(num2 instanceof Number) // true
var str2 = new String()
console.log(str2 instanceof String) // true
instanceof 前为我们需要检测的变量,后面是需要判断是否有继承关系的对象,返回一个布尔值表示是否存在继承关系
var a = []
a instanceof Array // true
a instanceof Object // true
var b = {}
b instanceof Array // false
b instance Object // true
var c = null
c instanceof Object // false
无法用 instanceof 来检测数字、字符串、布尔、Null 和 Undefined 类型
方法三:通过调用 constructor 来识别
undefined 和 null 没有 contructor 属性
const a = []
console.log(a.constructor)
方法四:使用 Object.prototype.toString.call(推荐)
可以用来检测 Object、Number、Array、Date、Function、String、Boolean、Error 和 RegExp。
它不能检测非原生构造函数的构造函数名。
Object.prototype.toString.call('1')
//["object String"]
Object.prototype.toString.call([])
//["object Array"]
Object.prototype.toString.call({})
//["object Object"]
如果手动改动对象的原型链,可以使用
Object.prototype.toString.call
进行类型判断